package com.example.CarManagement.sys.controller;

import com.example.CarManagement.common.Result;
import com.example.CarManagement.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件的上传和下载
 */

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${imgSave.path}")
    private String basePath;

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {

        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 使用UUID重新生成文件，防止原始文件一致覆盖文件的情况
        String filename = UUID.randomUUID().toString() + suffix;

        // 创建目录
        File mkFile = new File(basePath);
        if (!mkFile.exists()) {
            // 目录不存在，则创建
            mkFile.mkdirs();
        }

        try {
            file.transferTo(new File(basePath + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.success(filename);
    }

    /**
     * 图片下载
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {

            // 输入流，通过输入流读取文件类容
            try {
                FileInputStream fileInputStream = new FileInputStream((new File(basePath + name)));
                // 输出流，通过输出流将文件写会浏览器，在浏览器展示图片
                ServletOutputStream outputStream = response.getOutputStream();

                response.setContentType("image/jpeg");

                int len = 0;
                byte[] bytes = new byte[1024];

                while ((len = fileInputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                    outputStream.flush();
                }

                // 关闭资源
                outputStream.close();
                fileInputStream.close();
            } catch (Exception e) {
                throw new ServiceException("文件不存在");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
